from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.banner_service import BannerService
from app.utils.auth import admin_required
from app.utils.response import success_response, error_response
from . import api

banner_ns = Namespace('banners', description='轮播图管理')

banner_model = banner_ns.model('Banner', {
    'title': fields.String(description='标题'),
    'image': fields.String(required=True, description='图片URL'),
    'link': fields.String(description='跳转链接'),
    'type': fields.Integer(description='类型 1首页 2分类'),
    'sort': fields.Integer(description='排序'),
    'status': fields.Boolean(description='状态')
})

@banner_ns.route('')
class BannerListAPI(Resource):
    method_decorators = [admin_required]

    def get(self, current_admin):
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        banner_type = request.args.get('type', type=int)
        try:
            items, total = BannerService.list_banners(banner_type, page, limit)
            return success_response({'data': items, 'page': page, 'limit': limit, 'total': total})
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

    @banner_ns.expect(banner_model)
    def post(self, current_admin):
        data = request.get_json() or {}
        try:
            banner = BannerService.create_banner(data)
            return success_response(banner, '创建成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

@banner_ns.route('/<int:banner_id>')
class BannerDetailAPI(Resource):
    method_decorators = [admin_required]

    @banner_ns.expect(banner_model)
    def put(self, banner_id, current_admin):
        data = request.get_json() or {}
        try:
            banner = BannerService.update_banner(banner_id, data)
            if not banner:
                return error_response('不存在', 404)
            return success_response(banner, '更新成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

    def delete(self, banner_id, current_admin):
        try:
            ok = BannerService.delete_banner(banner_id)
            if not ok:
                return error_response('不存在', 404)
            return success_response(message='删除成功')
        except Exception as e:
            current_app.logger.error(str(e))
            return error_response(str(e), 500)

api.add_namespace(banner_ns) 